package com.smalls.newvideotwo.view;

import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.smalls.newvideotwo.util.LogUtil;
import com.smalls.newvideotwo.utils.Constant;

public class MyGridLayoutManager extends GridLayoutManager {
    private static String TAG = Constant.baddcoolio2tag? Constant.TAGPREFIXSTR + MyGridLayoutManager.class.getSimpleName():MyGridLayoutManager.class.getSimpleName();

    public MyGridLayoutManager(Context context, int spanCount) {
        super(context, spanCount);
    }

    public int getFocusedChildPosition() {
        int position = -1;
        View child = getFocusedChild();
        LogUtil.i(TAG, "getFocusedChild(),child = " + child);
        if (null != child) {
            position = getPosition(child);
        } else {
            LogUtil.e(TAG, "getFocusedChild(),child == null , and return -1 !!!!!!!!!!");
        }
        return position;
    }

    @Override
    public View onInterceptFocusSearch(View focused, int direction) {
        //LogUtil.i(TAG, "onInterceptFocusSearch , focused = " + focused + " direction = " + direction);
        int span = getSpanCount();
        int count = getItemCount();
        int fromPos = getPosition(focused);

        switch (direction) {
            case View.FOCUS_UP:
                fromPos = (fromPos - span);
                break;
            case View.FOCUS_DOWN:
                fromPos = (fromPos + span);
                if (fromPos >= count) {
                    return findViewByPosition(count);
                }
                break;
            case View.FOCUS_RIGHT:
                fromPos++;
                break;
            case View.FOCUS_LEFT:
                fromPos--;
                break;
        }

        LogUtil.i(TAG, "onInterceptFocusSearch , fromPos = " + fromPos + " count = " + count + " span = " + span);
        if (fromPos < 0) {
            return focused;
        } else if (fromPos >= count) {
            return focused;
        } else {
            return findViewByPosition(fromPos);
//            return getChildAt(fromPos);
        }
    }

    @Override
    public View onFocusSearchFailed(View focused, int focusDirection, RecyclerView.Recycler recycler, RecyclerView.State state) {
        if (focusDirection == View.FOCUS_DOWN) {
            int fromPos = getPosition(focused);
            fromPos = fromPos + getSpanCount();
            if (findViewByPosition(fromPos) != null) {
                return findViewByPosition(fromPos);
            }
            return focused;
        }
        return super.onFocusSearchFailed(focused, focusDirection, recycler, state);
    }
}
